#include "mainWindow.h"
#include "cpuSimulator.h"
#include "interruptManager.h"
#include <QApplication>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QTextCursor>
#include <QTextDocument>
#include <QTextBlock>
#include <QHeaderView>
#include <QSplitter>
#include <QTextStream>
#include <QDebug>

/**
 * @brief MainWindow构造函数
 * @param parent 父窗口指针
 */
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , cpuSimulator(std::unique_ptr<CpuSimulator>(new CpuSimulator(this)))
    , interruptManager(std::unique_ptr<InterruptManager>(new InterruptManager(this)))
    , mainTabWidget(nullptr)
    , mainSplitter(nullptr)
    , rightSplitter(nullptr)
    , codeEditor(nullptr)
    , instructionTable(nullptr)
    , registerTable(nullptr)
    , memoryTable(nullptr)
    , outputTextEdit(nullptr)
    , logTextEdit(nullptr)
    , statusLabel(nullptr)
    , cpuStateLabel(nullptr)
    , instructionCountLabel(nullptr)
    , memoryUsageLabel(nullptr)
    , executionProgress(nullptr)
    , statusUpdateTimer(new QTimer(this))
    , currentFileName("")
    , isModified(false)
    , currentInstructionIndex(-1)
    , isExecuting(false)
    , autoSaveEnabled(false)
    , memoryViewSize(256)
    , showLineNumbers(true)
    , lastErrorMessage("")
    , consecutiveErrorCount(0)
    , errorClearTimer(new QTimer(this))
{
    // 设置CPU模拟器使用MainWindow的中断管理器
    if (cpuSimulator && interruptManager) {
        cpuSimulator->setInterruptManager(interruptManager.get());
        qDebug() << "MainWindow: CPU模拟器已连接到MainWindow的中断管理器";
    }
    
    setupUi();
    connectSignals();
    readSettings();
    
    // 设置默认字体
    codeEditorFont = QFont("Consolas", 11);
    if (codeEditor) {
        codeEditor->setFont(codeEditorFont);
    }
    
    // 启动状态更新定时器
    statusUpdateTimer->start(1000); // 每秒更新一次
    
    // 配置错误清除定时器
    errorClearTimer->setSingleShot(true);
    errorClearTimer->setInterval(5000); // 5秒后清除错误状态
    connect(errorClearTimer, &QTimer::timeout, this, &MainWindow::clearErrorState);
    
    // 初始化状态
    updateToolbarActions();
    updateStatusBar();
    
    // 加载示例代码
    loadSampleCode();
}

/**
 * @brief MainWindow析构函数
 */
MainWindow::~MainWindow()
{
    writeSettings();
}

/**
 * @brief 关闭事件处理
 * @param event 关闭事件
 */
void MainWindow::closeEvent(QCloseEvent *event)
{
    if (maybeSave()) {
        writeSettings();
        event->accept();
    } else {
        event->ignore();
    }
}

/**
 * @brief 设置用户界面
 */
void MainWindow::setupUi()
{
    // 设置窗口属性
    setWindowTitle("Qt汇编程序解释器 - 扩展版");
    setMinimumSize(1000, 700);
    resize(1200, 800);
    
    createMenus();
    createToolBars();
    createStatusBar();
    createCentralWidget();
}

/**
 * @brief 创建菜单
 */
void MainWindow::createMenus()
{
    // 文件菜单
    fileMenu = menuBar()->addMenu(tr("文件(&F)"));
    
    newAct = new QAction(tr("新建"), this);
    newAct->setShortcut(QKeySequence::New);
    newAct->setStatusTip(tr("新建汇编程序文件"));
    fileMenu->addAction(newAct);
    
    openAct = new QAction(tr("打开"), this);
    openAct->setShortcut(QKeySequence::Open);
    openAct->setStatusTip(tr("打开汇编程序文件"));
    fileMenu->addAction(openAct);
    
    fileMenu->addSeparator();
    
    saveAct = new QAction(tr("保存"), this);
    saveAct->setShortcut(QKeySequence::Save);
    saveAct->setStatusTip(tr("保存当前文件"));
    fileMenu->addAction(saveAct);
    
    saveAsAct = new QAction(tr("另存为..."), this);
    saveAsAct->setShortcut(QKeySequence::SaveAs);
    saveAsAct->setStatusTip(tr("将文件另存为新文件"));
    fileMenu->addAction(saveAsAct);
    
    fileMenu->addSeparator();
    
    exitAct = new QAction(tr("退出"), this);
    exitAct->setShortcut(tr("Ctrl+Q"));
    exitAct->setStatusTip(tr("退出应用程序"));
    fileMenu->addAction(exitAct);
    
    // 编辑菜单
    editMenu = menuBar()->addMenu(tr("编辑(&E)"));
    
    undoAct = new QAction(tr("撤销"), this);
    undoAct->setShortcut(QKeySequence::Undo);
    editMenu->addAction(undoAct);
    
    redoAct = new QAction(tr("重做"), this);
    redoAct->setShortcut(QKeySequence::Redo);
    editMenu->addAction(redoAct);
    
    editMenu->addSeparator();
    
    cutAct = new QAction(tr("剪切"), this);
    cutAct->setShortcut(QKeySequence::Cut);
    editMenu->addAction(cutAct);
    
    copyAct = new QAction(tr("复制"), this);
    copyAct->setShortcut(QKeySequence::Copy);
    editMenu->addAction(copyAct);
    
    pasteAct = new QAction(tr("粘贴"), this);
    pasteAct->setShortcut(QKeySequence::Paste);
    editMenu->addAction(pasteAct);
    
    editMenu->addSeparator();
    
    findAct = new QAction(tr("查找"), this);
    findAct->setShortcut(QKeySequence::Find);
    editMenu->addAction(findAct);
    
    replaceAct = new QAction(tr("替换"), this);
    replaceAct->setShortcut(tr("Ctrl+H"));
    editMenu->addAction(replaceAct);
    
    // 运行菜单
    runMenu = menuBar()->addMenu(tr("运行(&R)"));
    
    runAct = new QAction(tr("运行"), this);
    runAct->setShortcut(tr("F5"));
    runAct->setStatusTip(tr("运行汇编程序"));
    runMenu->addAction(runAct);
    
    stepAct = new QAction(tr("单步"), this);
    stepAct->setShortcut(tr("F10"));
    stepAct->setStatusTip(tr("单步执行一条指令"));
    runMenu->addAction(stepAct);
    
    pauseAct = new QAction(tr("暂停"), this);
    pauseAct->setShortcut(tr("F6"));
    pauseAct->setStatusTip(tr("暂停程序执行"));
    runMenu->addAction(pauseAct);
    
    stopAct = new QAction(tr("停止"), this);
    stopAct->setShortcut(tr("Shift+F5"));
    stopAct->setStatusTip(tr("停止程序执行"));
    runMenu->addAction(stopAct);
    
    runMenu->addSeparator();
    
    resetAct = new QAction(tr("重置"), this);
    resetAct->setShortcut(tr("Ctrl+R"));
    resetAct->setStatusTip(tr("重置CPU状态"));
    runMenu->addAction(resetAct);
    
    // 调试菜单
    debugMenu = menuBar()->addMenu(tr("调试(&D)"));
    
    toggleBreakpointAct = new QAction(tr("切换断点"), this);
    toggleBreakpointAct->setShortcut(tr("F9"));
    debugMenu->addAction(toggleBreakpointAct);
    
    clearBreakpointsAct = new QAction(tr("清除所有断点"), this);
    debugMenu->addAction(clearBreakpointsAct);
    
    debugMenu->addSeparator();
    
    viewMemoryAct = new QAction(tr("内存查看器"), this);
    debugMenu->addAction(viewMemoryAct);
    
    viewStatsAct = new QAction(tr("中断统计"), this);
    debugMenu->addAction(viewStatsAct);
    
    // 帮助菜单
    helpMenu = menuBar()->addMenu(tr("帮助(&H)"));
    
    loadExampleAct = new QAction(tr("加载示例"), this);
    loadExampleAct->setStatusTip(tr("加载示例汇编程序"));
    helpMenu->addAction(loadExampleAct);
    
    helpMenu->addSeparator();
    
    helpAct = new QAction(tr("帮助"), this);
    helpAct->setShortcut(tr("F1"));
    helpMenu->addAction(helpAct);
    
    aboutAct = new QAction(tr("关于"), this);
    helpMenu->addAction(aboutAct);
}

/**
 * @brief 创建工具栏
 */
void MainWindow::createToolBars()
{
    // 文件工具栏
    fileToolBar = addToolBar(tr("文件"));
    fileToolBar->addAction(newAct);
    fileToolBar->addAction(openAct);
    fileToolBar->addAction(saveAct);
    fileToolBar->addSeparator();
    fileToolBar->addAction(loadExampleAct);
    
    // 编辑工具栏
    editToolBar = addToolBar(tr("编辑"));
    editToolBar->addAction(undoAct);
    editToolBar->addAction(redoAct);
    editToolBar->addSeparator();
    editToolBar->addAction(cutAct);
    editToolBar->addAction(copyAct);
    editToolBar->addAction(pasteAct);
    
    // 运行工具栏
    runToolBar = addToolBar(tr("运行"));
    runToolBar->addAction(runAct);
    runToolBar->addAction(stepAct);
    runToolBar->addAction(pauseAct);
    runToolBar->addAction(stopAct);
    runToolBar->addSeparator();
    runToolBar->addAction(resetAct);
}

/**
 * @brief 创建状态栏
 */
void MainWindow::createStatusBar()
{
    statusLabel = new QLabel(tr("就绪"));
    statusBar()->addWidget(statusLabel);
    
    cpuStateLabel = new QLabel(tr("CPU: 停止"));
    statusBar()->addWidget(cpuStateLabel);
    
    instructionCountLabel = new QLabel(tr("指令: 0"));
    statusBar()->addWidget(instructionCountLabel);
    
    memoryUsageLabel = new QLabel(tr("内存: 0KB"));
    statusBar()->addWidget(memoryUsageLabel);
    
    executionProgress = new QProgressBar();
    executionProgress->setVisible(false);
    statusBar()->addPermanentWidget(executionProgress);
}

/**
 * @brief 创建中央窗口部件
 */
void MainWindow::createCentralWidget()
{
    QWidget *centralWidget = new QWidget;
    setCentralWidget(centralWidget);
    
    QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);
    
    // 创建主分割器
    mainSplitter = new QSplitter(Qt::Horizontal);
    mainLayout->addWidget(mainSplitter);
    
    // 创建左侧标签页
    QTabWidget *leftTabWidget = new QTabWidget;
    leftTabWidget->setMinimumWidth(400);
    
    // 代码编辑器标签页
    QWidget *codeTab = createCodeEditor();
    leftTabWidget->addTab(codeTab, tr("代码编辑器"));
    
    // 指令列表标签页
    QWidget *instructionTab = createInstructionView();
    leftTabWidget->addTab(instructionTab, tr("指令列表"));
    
    mainSplitter->addWidget(leftTabWidget);
    
    // 创建右侧标签页
    QTabWidget *rightTabWidget = new QTabWidget;
    rightTabWidget->setMinimumWidth(400);
    
    // 寄存器标签页
    QWidget *registerTab = createRegisterView();
    rightTabWidget->addTab(registerTab, tr("寄存器"));
    
    // 内存标签页
    QWidget *memoryTab = createMemoryView();
    rightTabWidget->addTab(memoryTab, tr("内存"));
    
    // 输出标签页
    QWidget *outputTab = createOutputView();
    rightTabWidget->addTab(outputTab, tr("输出"));
    
    mainSplitter->addWidget(rightTabWidget);
    
    // 设置分割器比例
    mainSplitter->setSizes({500, 500});
}

/**
 * @brief 创建代码编辑器
 * @return QWidget* 代码编辑器窗口部件
 */
QWidget* MainWindow::createCodeEditor()
{
    QWidget *widget = new QWidget;
    QVBoxLayout *layout = new QVBoxLayout(widget);
    
    codeEditor = new QTextEdit;
    codeEditor->setFont(QFont("Consolas", 11));
    codeEditor->setLineWrapMode(QTextEdit::NoWrap);
    codeEditor->setPlaceholderText(tr("请在此输入汇编代码...\n\n示例：\nMOV AX, $10\nMOV BX, $20\nADD AX, BX\nINT 0x22    ; 输出整数\nHLT         ; 停机"));
    
    layout->addWidget(codeEditor);
    
    return widget;
}

/**
 * @brief 创建寄存器视图
 * @return QWidget* 寄存器视图窗口部件
 */
QWidget* MainWindow::createRegisterView()
{
    QWidget *widget = new QWidget;
    QVBoxLayout *layout = new QVBoxLayout(widget);
    
    registerTable = new QTableWidget;
    registerTable->setColumnCount(3);
    
    QStringList headers;
    headers << tr("寄存器") << tr("十进制值") << tr("十六进制值");
    registerTable->setHorizontalHeaderLabels(headers);
    
    registerTable->horizontalHeader()->setStretchLastSection(true);
    registerTable->setAlternatingRowColors(true);
    registerTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    
    layout->addWidget(registerTable);
    
    return widget;
}

/**
 * @brief 创建内存视图
 * @return QWidget* 内存视图窗口部件
 */
QWidget* MainWindow::createMemoryView()
{
    QWidget *widget = new QWidget;
    QVBoxLayout *layout = new QVBoxLayout(widget);
    
    memoryTable = new QTableWidget;
    memoryTable->setColumnCount(4);
    
    QStringList headers;
    headers << tr("地址") << tr("十进制值") << tr("十六进制值") << tr("字符");
    memoryTable->setHorizontalHeaderLabels(headers);
    
    memoryTable->horizontalHeader()->setStretchLastSection(true);
    memoryTable->setAlternatingRowColors(true);
    memoryTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    
    layout->addWidget(memoryTable);
    
    return widget;
}

/**
 * @brief 创建输出视图
 * @return QWidget* 输出视图窗口部件
 */
QWidget* MainWindow::createOutputView()
{
    QWidget *widget = new QWidget;
    QVBoxLayout *layout = new QVBoxLayout(widget);
    
    QSplitter *outputSplitter = new QSplitter(Qt::Vertical);
    
    outputTextEdit = new QTextEdit;
    outputTextEdit->setReadOnly(true);
    outputTextEdit->setFont(QFont("Consolas", 10));
    outputTextEdit->setPlaceholderText(tr("程序输出将显示在这里..."));
    
    logTextEdit = new QTextEdit;
    logTextEdit->setReadOnly(true);
    logTextEdit->setFont(QFont("Consolas", 9));
    logTextEdit->setPlaceholderText(tr("系统日志将显示在这里..."));
    logTextEdit->setMaximumHeight(150);
    
    outputSplitter->addWidget(outputTextEdit);
    outputSplitter->addWidget(logTextEdit);
    outputSplitter->setSizes({400, 150});
    
    layout->addWidget(outputSplitter);
    
    return widget;
}

/**
 * @brief 创建指令视图
 * @return QWidget* 指令视图窗口部件
 */
QWidget* MainWindow::createInstructionView()
{
    QWidget *widget = new QWidget;
    QVBoxLayout *layout = new QVBoxLayout(widget);
    
    instructionTable = new QTableWidget;
    instructionTable->setColumnCount(4);
    
    QStringList headers;
    headers << tr("行号") << tr("地址") << tr("指令") << tr("操作数");
    instructionTable->setHorizontalHeaderLabels(headers);
    
    instructionTable->horizontalHeader()->setStretchLastSection(true);
    instructionTable->setAlternatingRowColors(true);
    instructionTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    
    layout->addWidget(instructionTable);
    
    return widget;
}

/**
 * @brief 连接信号和槽
 */
void MainWindow::connectSignals()
{
    // 文件操作
    connect(newAct, &QAction::triggered, this, &MainWindow::onNewFile);
    connect(openAct, &QAction::triggered, this, &MainWindow::onOpenFile);
    connect(saveAct, &QAction::triggered, this, &MainWindow::onSaveFile);
    connect(saveAsAct, &QAction::triggered, this, &MainWindow::onSaveAsFile);
    connect(exitAct, &QAction::triggered, this, &MainWindow::onExit);
    
    // 编辑操作
    connect(undoAct, &QAction::triggered, this, &MainWindow::onUndo);
    connect(redoAct, &QAction::triggered, this, &MainWindow::onRedo);
    connect(cutAct, &QAction::triggered, this, &MainWindow::onCut);
    connect(copyAct, &QAction::triggered, this, &MainWindow::onCopy);
    connect(pasteAct, &QAction::triggered, this, &MainWindow::onPaste);
    connect(findAct, &QAction::triggered, this, &MainWindow::onFind);
    connect(replaceAct, &QAction::triggered, this, &MainWindow::onReplace);
    
    // 运行控制
    connect(runAct, &QAction::triggered, this, &MainWindow::onRunProgram);
    connect(stepAct, &QAction::triggered, this, &MainWindow::onStepExecution);
    connect(pauseAct, &QAction::triggered, this, &MainWindow::onPauseProgram);
    connect(stopAct, &QAction::triggered, this, &MainWindow::onStopProgram);
    connect(resetAct, &QAction::triggered, this, &MainWindow::onResetCpu);
    
    // 调试操作
    connect(toggleBreakpointAct, &QAction::triggered, this, &MainWindow::onToggleBreakpoint);
    connect(clearBreakpointsAct, &QAction::triggered, this, &MainWindow::onClearAllBreakpoints);
    connect(viewMemoryAct, &QAction::triggered, this, &MainWindow::onViewMemory);
    connect(viewStatsAct, &QAction::triggered, this, &MainWindow::onViewInterruptStatistics);
    
    // 帮助操作
    connect(loadExampleAct, &QAction::triggered, this, &MainWindow::onLoadExample);
    connect(helpAct, &QAction::triggered, this, &MainWindow::onShowHelp);
    connect(aboutAct, &QAction::triggered, this, &MainWindow::onAbout);
    
    // CPU状态更新
    if (cpuSimulator) {
        connect(cpuSimulator.get(), &CpuSimulator::stateChanged, this, &MainWindow::onCpuStateChanged);
        connect(cpuSimulator.get(), &CpuSimulator::registerChanged, this, &MainWindow::onRegisterChanged);
        connect(cpuSimulator.get(), &CpuSimulator::memoryChanged, this, &MainWindow::onMemoryChanged);
        connect(cpuSimulator.get(), &CpuSimulator::instructionExecuted, this, &MainWindow::onInstructionExecuted);
        connect(cpuSimulator.get(), &CpuSimulator::errorOccurred, this, &MainWindow::onCpuError);
    }
    
    // 中断管理器信号连接
    if (interruptManager) {
        // 开启调试模式，便于跟踪信号传递
        interruptManager->setDebugMode(true);
        qDebug() << "主窗口: InterruptManager调试模式已开启";
        
        connect(interruptManager.get(), &InterruptManager::outputMessage, this, &MainWindow::onOutputMessage);
        connect(interruptManager.get(), &InterruptManager::errorOccurred, this, &MainWindow::onInterruptError);
        
        qDebug() << "主窗口: InterruptManager信号连接已建立";
    }
    
    // 代码编辑器
    if (codeEditor) {
        connect(codeEditor, &QTextEdit::textChanged, this, &MainWindow::onTextChanged);
    }
    
    // 状态更新定时器
    connect(statusUpdateTimer, &QTimer::timeout, this, &MainWindow::updateStatusBar);
}

// 文件操作槽函数
void MainWindow::onNewFile()
{
    if (maybeSave()) {
        codeEditor->clear();
        setCurrentFile("");
        loadSampleCode();
    }
}

void MainWindow::onOpenFile()
{
    if (maybeSave()) {
        QString fileName = QFileDialog::getOpenFileName(this, tr("打开汇编文件"), "", tr("汇编文件 (*.asm *.s);;所有文件 (*)"));
        if (!fileName.isEmpty()) {
            loadFromFile(fileName);
        }
    }
}

void MainWindow::onSaveFile()
{
    if (currentFileName.isEmpty()) {
        onSaveAsFile();
    } else {
        saveToFile(currentFileName);
    }
}

void MainWindow::onSaveAsFile()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("保存汇编文件"), "", tr("汇编文件 (*.asm *.s);;所有文件 (*)"));
    if (!fileName.isEmpty()) {
        saveToFile(fileName);
    }
}

void MainWindow::onExit()
{
    close();
}

// 编辑操作槽函数
void MainWindow::onUndo()
{
    if (codeEditor) {
        codeEditor->undo();
    }
}

void MainWindow::onRedo()
{
    if (codeEditor) {
        codeEditor->redo();
    }
}

void MainWindow::onCut()
{
    if (codeEditor) {
        codeEditor->cut();
    }
}

void MainWindow::onCopy()
{
    if (codeEditor) {
        codeEditor->copy();
    }
}

void MainWindow::onPaste()
{
    if (codeEditor) {
        codeEditor->paste();
    }
}

void MainWindow::onFind()
{
    QMessageBox::information(this, tr("查找"), tr("查找功能尚未实现"));
}

void MainWindow::onReplace()
{
    QMessageBox::information(this, tr("替换"), tr("替换功能尚未实现"));
}

// 运行控制槽函数
void MainWindow::onRunProgram()
{
    if (!cpuSimulator) return;
    
    QString code = codeEditor->toPlainText();
    if (code.trimmed().isEmpty()) {
        QMessageBox::warning(this, tr("警告"), tr("请先输入汇编代码"));
        return;
    }
    
    if (cpuSimulator->loadProgram(code)) {
        isExecuting = true;
        updateToolbarActions();
        executionProgress->setVisible(true);
        
        // 更新指令视图
        updateInstructionView();
        
        // 开始执行
        if (cpuSimulator->executeProgram()) {
            logTextEdit->append(tr("程序开始执行..."));
            
            // 清除之前的错误状态
            clearErrorState();
        }
    } else {
        QString errorMsg = tr("程序加载失败");
        
        // 在日志中记录程序加载失败信息
        logTextEdit->append(errorMsg);
        
        // 在状态栏显示错误提示
        if (statusLabel) {
            statusLabel->setText(tr("错误: %1").arg(errorMsg));
            statusLabel->setStyleSheet("color: red;");
        }
        
        // 使用智能错误对话框显示
        if (shouldShowErrorDialog(errorMsg)) {
            QMessageBox* errorBox = new QMessageBox(QMessageBox::Critical, tr("错误"), errorMsg, QMessageBox::Ok, this);
            errorBox->setAttribute(Qt::WA_DeleteOnClose);
            errorBox->setModal(false);
            errorBox->show();
        }
        
        // 启动错误清除定时器
        errorClearTimer->start();
    }
}

void MainWindow::onStepExecution()
{
    if (!cpuSimulator) return;
    
    if (!isExecuting) {
        // 如果程序没有运行，先加载程序
        onRunProgram();
        return;
    }
    
    if (cpuSimulator->stepExecution()) {
        updateRegisterView();
        updateMemoryView();
        highlightCurrentInstruction();
    }
}

void MainWindow::onPauseProgram()
{
    if (cpuSimulator && isExecuting) {
        cpuSimulator->pauseExecution();
        updateToolbarActions();
    }
}

void MainWindow::onStopProgram()
{
    if (cpuSimulator) {
        cpuSimulator->stopExecution();
        isExecuting = false;
        executionProgress->setVisible(false);
        updateToolbarActions();
        logTextEdit->append(tr("程序执行已停止"));
    }
}

void MainWindow::onResetCpu()
{
    if (cpuSimulator) {
        cpuSimulator->resetCpu();
        isExecuting = false;
        executionProgress->setVisible(false);
        updateToolbarActions();
        updateRegisterView();
        updateMemoryView();
        updateInstructionView();
        logTextEdit->append(tr("CPU已重置"));
    }
}

// 调试操作槽函数
void MainWindow::onToggleBreakpoint()
{
    QMessageBox::information(this, tr("断点"), tr("断点功能尚未实现"));
}

void MainWindow::onClearAllBreakpoints()
{
    QMessageBox::information(this, tr("断点"), tr("清除断点功能尚未实现"));
}

void MainWindow::onViewMemory()
{
    QMessageBox::information(this, tr("内存查看器"), tr("内存查看器功能尚未实现"));
}

void MainWindow::onViewInterruptStatistics()
{
    QMessageBox::information(this, tr("中断统计"), tr("中断统计功能尚未实现"));
}

// 帮助操作槽函数
void MainWindow::onLoadExample()
{
    loadSampleCode();
    
    // 测试信号链是否工作
    qDebug() << "测试：手动触发InterruptManager的outputMessage信号";
    if (interruptManager) {
        // 创建一个测试信号发射
        QTimer::singleShot(1000, this, [this]() {
            qDebug() << "测试：1秒后发射测试消息";
            if (interruptManager) {
                // 直接通过InterruptManager发射信号进行测试
                QMetaObject::invokeMethod(interruptManager.get(), 
                    [this]() {
                        qDebug() << "测试：InterruptManager发射信号";
                        emit interruptManager->outputMessage("=== 信号链测试消息 ===");
                    }, Qt::QueuedConnection);
            }
        });
    }
}

void MainWindow::onShowHelp()
{
    QString helpText = tr("Qt汇编程序解释器 - 扩展版\n\n"
                         "支持的指令:\n"
                         "MOV, ADD, SUB, MUL, DIV, CMP, JMP, JE, INT, HLT\n\n"
                         "中断调用:\n"
                         "INT 0x10-0x1F: 文件操作\n"
                         "INT 0x20-0x2F: 输入输出\n"
                         "INT 0x30-0x3F: 字符串操作\n"
                         "INT 0x40-0x4F: 数学运算\n"
                         "INT 0x50-0x5F: 系统信息\n\n"
                         "快捷键:\n"
                         "F5: 运行程序\n"
                         "F10: 单步执行\n"
                         "F6: 暂停执行\n"
                         "Shift+F5: 停止执行\n"
                         "Ctrl+R: 重置CPU");
    
    QMessageBox::information(this, tr("帮助"), helpText);
}

void MainWindow::onAbout()
{
    QString aboutText = tr("Qt汇编程序解释器 - 扩展版 v1.0\n\n"
                          "基于Qt框架开发的汇编程序模拟器\n"
                          "支持96个中断调用，提供丰富的系统功能\n\n"
                          "开发者: AI助手\n"
                          "技术栈: Qt 5.15+ / C++17\n"
                          "架构: 模块化设计，支持扩展");
    
    QMessageBox::about(this, tr("关于"), aboutText);
}

// CPU状态更新槽函数
void MainWindow::onCpuStateChanged(CpuState newState)
{
    QString stateText;
    switch (newState) {
        case CpuState::Stopped:
            stateText = tr("停止");
            isExecuting = false;
            break;
        case CpuState::Running:
            stateText = tr("运行");
            isExecuting = true;
            break;
        case CpuState::Paused:
            stateText = tr("暂停");
            break;
        case CpuState::Error:
            stateText = tr("错误");
            isExecuting = false;
            break;
        case CpuState::Halted:
            stateText = tr("停机");
            isExecuting = false;
            break;
    }
    
    cpuStateLabel->setText(tr("CPU: %1").arg(stateText));
    updateToolbarActions(newState);
}

void MainWindow::onRegisterChanged(const QString& registerName, int newValue)
{
    Q_UNUSED(registerName)
    Q_UNUSED(newValue)
    updateRegisterView();
}

void MainWindow::onMemoryChanged(int address, int newValue)
{
    Q_UNUSED(address)
    Q_UNUSED(newValue)
    updateMemoryView();
}

void MainWindow::onInstructionExecuted(const Instruction& instruction)
{
    logTextEdit->append(tr("执行指令: %1").arg(instruction.originalText));
    highlightCurrentInstruction();
}

void MainWindow::onCpuError(const QString& errorMessage)
{
    // 在日志中记录详细错误信息
    logTextEdit->append(tr("CPU错误: %1").arg(errorMessage));
    
    // 在状态栏显示错误提示
    if (statusLabel) {
        statusLabel->setText(tr("错误: %1").arg(errorMessage));
        statusLabel->setStyleSheet("color: red;");
    }
    
    // 立即停止程序执行，防止错误累积
    if (cpuSimulator && isExecuting) {
        cpuSimulator->stopExecution();
        isExecuting = false;
        if (executionProgress) {
            executionProgress->setVisible(false);
        }
        updateToolbarActions();
        logTextEdit->append(tr("程序因错误已停止执行"));
    }
    
    // 智能错误对话框显示：避免重复显示相同错误
    if (shouldShowErrorDialog(errorMessage)) {
        QMessageBox* errorBox = new QMessageBox(QMessageBox::Critical, tr("CPU错误"), errorMessage, QMessageBox::Ok, this);
        errorBox->setAttribute(Qt::WA_DeleteOnClose);
        errorBox->setModal(false);
        errorBox->show();
        
        // 如果连续错误超过1次，在对话框中提示用户
        if (consecutiveErrorCount > 1) {
            errorBox->setText(tr("CPU错误 (第%1次)").arg(consecutiveErrorCount));
            errorBox->setInformativeText(tr("相同错误: %1\n\n连续出现%2次错误后将不再显示对话框。")
                                        .arg(errorMessage)
                                        .arg(consecutiveErrorCount));
        }
    } else {
        // 记录被抑制的错误
        logTextEdit->append(tr("错误对话框已被抑制（连续相同错误超过3次）"));
    }
    
    // 启动错误清除定时器
    errorClearTimer->start();
}

void MainWindow::onOutputMessage(const QString& message)
{
    qDebug() << "输出消息:" << message;
    if (outputTextEdit) {
        outputTextEdit->append(message);
    }
    if (logTextEdit) {
        logTextEdit->append(QString("输出: %1").arg(message));
    }
}

void MainWindow::onTextChanged()
{
    isModified = true;
    setWindowModified(true);
}

// 界面更新方法
void MainWindow::updateStatusBar()
{
    if (cpuSimulator) {
        int instructionCount = cpuSimulator->getProgramSize();
        instructionCountLabel->setText(tr("指令: %1").arg(instructionCount));
        
        // 简单的内存使用计算（示例）
        memoryUsageLabel->setText(tr("内存: %1KB").arg(instructionCount * 4 / 1024.0, 0, 'f', 1));
        
        // 如果状态栏显示错误信息，当程序正常运行时清除错误状态
        if (statusLabel && isExecuting && cpuSimulator->getState() == CpuState::Running) {
            statusLabel->setText(tr("程序运行中..."));
            statusLabel->setStyleSheet("color: green;");
        } else if (statusLabel && !isExecuting && cpuSimulator->getState() == CpuState::Stopped) {
            statusLabel->setText(tr("就绪"));
            statusLabel->setStyleSheet("color: black;");
        }
    }
}

void MainWindow::updateToolbarActions(CpuState currentState)
{
    bool canRun = !isExecuting;
    bool canStop = isExecuting;
    bool canStep = !isExecuting || (currentState == CpuState::Paused);
    
    runAct->setEnabled(canRun);
    stepAct->setEnabled(canStep);
    pauseAct->setEnabled(isExecuting);
    stopAct->setEnabled(canStop);
    resetAct->setEnabled(true);
}

void MainWindow::updateToolbarActions()
{
    if (cpuSimulator) {
        updateToolbarActions(cpuSimulator->getState());
    } else {
        updateToolbarActions(CpuState::Stopped);
    }
}

void MainWindow::updateRegisterView()
{
    if (!cpuSimulator || !registerTable) return;
    
    QMap<QString, int> registers = cpuSimulator->getAllRegisters();
    
    registerTable->setRowCount(registers.size());
    int row = 0;
    
    for (auto it = registers.begin(); it != registers.end(); ++it) {
        registerTable->setItem(row, 0, new QTableWidgetItem(it.key()));
        registerTable->setItem(row, 1, new QTableWidgetItem(QString::number(it.value())));
        registerTable->setItem(row, 2, new QTableWidgetItem(QString("0x%1").arg(it.value(), 4, 16, QChar('0')).toUpper()));
        row++;
    }
}

void MainWindow::updateMemoryView()
{
    if (!cpuSimulator || !memoryTable) return;
    
    memoryTable->setRowCount(memoryViewSize);
    
    for (int i = 0; i < memoryViewSize; ++i) {
        int value = cpuSimulator->getMemory(i);
        memoryTable->setItem(i, 0, new QTableWidgetItem(QString("0x%1").arg(i, 4, 16, QChar('0')).toUpper()));
        memoryTable->setItem(i, 1, new QTableWidgetItem(QString::number(value)));
        memoryTable->setItem(i, 2, new QTableWidgetItem(QString("0x%1").arg(value, 2, 16, QChar('0')).toUpper()));
        
        QChar ch = (value >= 32 && value <= 126) ? QChar(value) : QChar('.');
        memoryTable->setItem(i, 3, new QTableWidgetItem(ch));
    }
}

void MainWindow::updateInstructionView()
{
    if (!cpuSimulator || !instructionTable) return;
    
    QList<Instruction> instructions = cpuSimulator->getInstructions();
    instructionTable->setRowCount(instructions.size());
    
    for (int i = 0; i < instructions.size(); ++i) {
        const Instruction& inst = instructions[i];
        instructionTable->setItem(i, 0, new QTableWidgetItem(QString::number(inst.lineNumber)));
        instructionTable->setItem(i, 1, new QTableWidgetItem(QString("0x%1").arg(i, 4, 16, QChar('0')).toUpper()));
        instructionTable->setItem(i, 2, new QTableWidgetItem(inst.mnemonic));
        instructionTable->setItem(i, 3, new QTableWidgetItem(inst.operands.join(", ")));
    }
}

void MainWindow::highlightCurrentInstruction()
{
    if (!cpuSimulator || !instructionTable) return;
    
    int currentIP = cpuSimulator->getInstructionPointer();
    if (currentIP >= 0 && currentIP < instructionTable->rowCount()) {
        instructionTable->selectRow(currentIP);
        instructionTable->scrollToItem(instructionTable->item(currentIP, 0));
    }
}

// 文件操作辅助方法
bool MainWindow::saveToFile(const QString& fileName)
{
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        // 使用非模态对话框提示文件保存失败
        QMessageBox* errorBox = new QMessageBox(QMessageBox::Warning, tr("保存文件"), 
                                                tr("无法写入文件 %1:\n%2").arg(fileName).arg(file.errorString()), 
                                                QMessageBox::Ok, this);
        errorBox->setAttribute(Qt::WA_DeleteOnClose);
        errorBox->setModal(false);
        errorBox->show();
        return false;
    }
    
    QTextStream out(&file);
    out << codeEditor->toPlainText();
    
    setCurrentFile(fileName);
    if (statusLabel) {
        statusLabel->setText(tr("文件已保存"));
        statusLabel->setStyleSheet("color: green;");
    }
    return true;
}

bool MainWindow::loadFromFile(const QString& fileName)
{
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        // 使用非模态对话框提示文件打开失败
        QMessageBox* errorBox = new QMessageBox(QMessageBox::Warning, tr("打开文件"), 
                                                tr("无法读取文件 %1:\n%2").arg(fileName).arg(file.errorString()), 
                                                QMessageBox::Ok, this);
        errorBox->setAttribute(Qt::WA_DeleteOnClose);
        errorBox->setModal(false);
        errorBox->show();
        return false;
    }
    
    QTextStream in(&file);
    codeEditor->setPlainText(in.readAll());
    
    setCurrentFile(fileName);
    if (statusLabel) {
        statusLabel->setText(tr("文件已打开"));
        statusLabel->setStyleSheet("color: green;");
    }
    return true;
}

bool MainWindow::maybeSave()
{
    if (!isModified) return true;
    
    const QMessageBox::StandardButton ret = QMessageBox::warning(this, tr("保存文件"),
                                                                 tr("文档已被修改。\n是否要保存更改？"),
                                                                 QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
    switch (ret) {
        case QMessageBox::Save:
            return onSaveFile(), true;
        case QMessageBox::Cancel:
            return false;
        default:
            break;
    }
    return true;
}

void MainWindow::setCurrentFile(const QString& fileName)
{
    currentFileName = fileName;
    isModified = false;
    setWindowModified(false);
    
    QString shownName = currentFileName;
    if (currentFileName.isEmpty()) {
        shownName = tr("untitled.asm");
    } else {
        shownName = strippedName(currentFileName);
    }
    
    setWindowTitle(tr("%1[*] - %2").arg(shownName).arg(tr("Qt汇编程序解释器")));
}

QString MainWindow::strippedName(const QString& fullFileName)
{
    return QFileInfo(fullFileName).fileName();
}

void MainWindow::loadSampleCode()
{
    codeEditor->setPlainText(getSampleCode());
    isModified = false;
    setWindowModified(false);
}

QString MainWindow::getSampleCode() const
{
    return tr("; Qt汇编程序解释器示例程序\n"
             "; 演示基本指令、内存操作和中断调用\n\n"
             "; 基本的数据传输和运算示例\n"
             "MOV AX, 10         ; 将10存入AX寄存器\n"
             "MOV BX, 20         ; 将20存入BX寄存器\n"
             "ADD AX, BX         ; AX = AX + BX (结果为30)\n\n"
             "; 内存操作示例 - 存储数据到内存\n"
             "MOV [100], AX      ; 将AX的值(30)存储到内存地址100\n"
             "MOV [101], BX      ; 将BX的值(20)存储到内存地址101\n"
             "MOV [102], 65      ; 将ASCII码65('A')存储到内存地址102\n\n"
             "; 显示结果 - 输出AX寄存器的值(30)\n"
             "INT 0x22           ; 中断调用 - 输出AX寄存器中的整数值\n\n"
             "; 更多计算\n"
             "MOV CX, 5          ; 将5存入CX寄存器\n"
             "SUB AX, CX         ; AX = AX - CX (30-5=25)\n"
             "MOV [103], AX      ; 将计算结果(25)存储到内存地址103\n"
             "INT 0x22           ; 再次输出AX寄存器的值(25)\n\n"
             "; 内存读取操作示例\n"
             "MOV DX, [100]      ; 从内存地址100读取值(30)到DX寄存器\n"
             "MOV [104], DX      ; 将DX的值存储到内存地址104\n\n"
             "; 字符输出示例\n"
             "MOV AX, [102]      ; 从内存地址102读取ASCII码(65)到AX\n"
             "INT 0x20           ; 中断调用 - 输出字符('A')\n\n"
             "; 内存数据处理示例\n"
             "MOV AX, [100]      ; 读取第一个数值(30)\n"
             "MOV BX, [101]      ; 读取第二个数值(20)\n"
             "ADD AX, BX         ; 计算和(50)\n"
             "MOV [105], AX      ; 将和存储到内存地址105\n"
             "INT 0x22           ; 输出计算结果(50)\n\n"
             "; 停机指令\n"
             "HLT                ; 停止执行\n\n"
             "; 预期输出结果:\n"
             "; 整数输出: 30     (第一个INT 0x22)\n"
             "; 整数输出: 25     (第二个INT 0x22)\n"
             "; A               (INT 0x20输出字符)\n"
             "; 整数输出: 50     (第三个INT 0x22)\n\n"
             "; 预期内存布局(地址: 值):\n"
             "; 100: 30 (AX的初始计算结果)\n"
             "; 101: 20 (BX的值)\n"
             "; 102: 65 (字符'A'的ASCII码)\n"
             "; 103: 25 (AX-CX的结果)\n"
             "; 104: 30 (从地址100复制的值)\n"
             "; 105: 50 (地址100和101的和)\n");
}

// 设置和配置方法
void MainWindow::readSettings()
{
    QSettings settings;
    restoreGeometry(settings.value("geometry").toByteArray());
    restoreState(settings.value("windowState").toByteArray());
}

void MainWindow::writeSettings()
{
    QSettings settings;
    settings.setValue("geometry", saveGeometry());
    settings.setValue("windowState", saveState());
}

// 占位实现其他槽函数
void MainWindow::onTabChanged(int index) { Q_UNUSED(index) }

void MainWindow::onInterruptHandled(int interruptNumber, const SystemCallResult& result) { 
    Q_UNUSED(interruptNumber) 
    Q_UNUSED(result)
    qDebug() << "中断处理完成:" << interruptNumber;
}

void MainWindow::onInterruptError(int interruptNumber, const QString& errorMessage) { 
    qDebug() << "中断错误:" << interruptNumber << errorMessage;
    if (logTextEdit) {
        logTextEdit->append(QString("中断错误 0x%1: %2").arg(interruptNumber, 2, 16, QChar('0')).arg(errorMessage));
    }
}

void MainWindow::applySettings() { /* 占位实现 */ }

/**
 * @brief 清除错误状态
 */
void MainWindow::clearErrorState()
{
    lastErrorMessage.clear();
    consecutiveErrorCount = 0;
    
    // 清除状态栏的错误显示
    if (statusLabel) {
        statusLabel->setText(tr("就绪"));
        statusLabel->setStyleSheet("color: black;");
    }
}

/**
 * @brief 判断是否应该显示错误对话框
 * @param errorMessage 错误消息
 * @return bool 是否应该显示对话框
 */
bool MainWindow::shouldShowErrorDialog(const QString& errorMessage)
{
    // 如果是相同的错误消息，增加计数器
    if (lastErrorMessage == errorMessage) {
        consecutiveErrorCount++;
        // 如果连续出现相同错误超过3次，就不再显示对话框
        if (consecutiveErrorCount > 3) {
            return false;
        }
    } else {
        // 如果是新的错误消息，重置计数器
        lastErrorMessage = errorMessage;
        consecutiveErrorCount = 1;
    }
    
    return true;
} 